package com.hxd.otc.utils.rongcloud;

import android.support.annotation.NonNull;
import android.text.TextUtils;

import com.hxd.otc.base.BaseApplication;
import com.hxd.otc.common.UserHelper;
import com.hxd.otc.module.my.bean.RongCloudTokenBean;
import com.hxd.otc.module.my.model.UserModel;
import com.hxd.otc.net.BaseObserver;
import com.hxd.otc.utils.LogUtils;

import io.rong.imkit.RongIM;
import io.rong.imkit.utils.SystemUtils;

/**
 * Created by lzy on 2019/1/17 0017.
 * description ${融云工具类}
 */
public class RongCloudUtils {
    private RongCloudUtils() {
    }

    private static class SingletonHolder {
        private static final RongCloudUtils instance = new RongCloudUtils();
    }

    public static RongCloudUtils getInstance() {
        return RongCloudUtils.SingletonHolder.instance;
    }

    private RongIMConnectCallBack mConnectCallback = new RongIMConnectCallBack();

    /**
     * 连接融云
     */
    public void connectRongCloud() {
        String rongCloudToken = UserHelper.getRongCloudToken();
        if (TextUtils.isEmpty(rongCloudToken)) {
            if (UserHelper.isLogin()) requestRongCloudToken();
        } else {
            connectRongCloud(rongCloudToken);
        }
    }

    /**
     * 通过融云token连接融云
     */
    private void connectRongCloud(String rongToken) {
        BaseApplication application = BaseApplication.getInstance();
        if (!application.getApplicationInfo().packageName.equals(SystemUtils.getCurProcessName(application)))
            return;

        RongIM.connect(rongToken, mConnectCallback);
    }

    /**
     * 请求融云token
     */
    public void requestRongCloudToken() {
        UserModel.getInstance().getRongCloudToken(new BaseObserver<RongCloudTokenBean>() {
            @Override
            public void onNext(@NonNull String msg, @NonNull RongCloudTokenBean rongCloudTokenBean) {
                if (rongCloudTokenBean == null) {
                    getRongCloudTokenFail("getRongCloudToken success but rongCloudTokenBean is null");
                    return;
                }
                String rongToken = rongCloudTokenBean.getToken();
                UserHelper.updateRongCloudToken(rongToken);
                getRongCloudTokenSuccess(rongToken);
            }

            @Override
            public void onError(int errType, @NonNull String errMessage) {
                getRongCloudTokenFail(errMessage);
            }
        });
    }

    /**
     * 获取融云token成功
     *
     * @param rongToken 融云token
     */
    private void getRongCloudTokenSuccess(String rongToken) {
        if (TextUtils.isEmpty(rongToken)) return;
        connectRongCloud(rongToken);
    }

    /**
     * 获取融云token失败
     *
     * @param errMessage 错误信息
     */
    private void getRongCloudTokenFail(String errMessage) {
        LogUtils.e("requestRongCloudToken errMessage:" + errMessage);
    }
}
